/**
 * This file is part of the dspace-poltman project http://www.poltman.com.
 *
 * This is free software; you can redistribute it and/or modify it under
 * the terms of DuraSpace DSpace license detailed in the LICENSE and NOTICE 
 * files at the root of the source tree and available online at
 * http://www.dspace.org/license/
 * 
 */
package com.poltman.dscentral.extended.services.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.poltman.dscentral.db.entity.dspace.EPersonEntity;
import com.poltman.dscentral.db.entity.pm.BaseUserEntity;
import com.poltman.dscentral.db.entity.pm.EPersonMenuGroupsEntity;
import com.poltman.dscentral.db.repository.dspace.EpersonRepository;
import com.poltman.dscentral.db.repository.pm.BaseUserRepository;
import com.poltman.dscentral.db.repository.pm.EPersonMenuGroupsRepository;
import com.poltman.dscentral.extended.services.EPersonExtendedService;

/**
 * 
 * @author Zbigniew Ciok; z.ciok@poltman.com
 * @version $Revision: 1523 $
 * 
 */
@Service("epersonExtendedService")
public class EPersonExtendedServiceImpl implements EPersonExtendedService {

	private static Logger log = Logger.getLogger(EPersonExtendedServiceImpl.class);

	private final EpersonRepository epersonRepository;
	private final BaseUserRepository baseUserRepository;
	private final EPersonMenuGroupsRepository epersonMenuGroupsRepository;

	@Autowired
	public EPersonExtendedServiceImpl(EpersonRepository epersonRepository, 
									  BaseUserRepository baseUserRepository,
									  EPersonMenuGroupsRepository epersonMenuGroupsRepository) {
		this.epersonRepository = epersonRepository;
		this.baseUserRepository = baseUserRepository;
		this.epersonMenuGroupsRepository = epersonMenuGroupsRepository;
	}

	@Transactional(rollbackFor=Exception.class)
	@Override
	public void addEPerson(EPersonEntity eperson, BaseUserEntity baseUser, List<String> userMenuShortcuts)  throws Exception {
		EPersonEntity epersonEntity = this.epersonRepository.save(eperson);
		if (baseUser != null) {
			baseUser.setEpersonId(epersonEntity.getEpersonId());
			this.baseUserRepository.save(baseUser);
			
			for (String shortcut : userMenuShortcuts) {
				
				EPersonMenuGroupsEntity userMenuGroup = new EPersonMenuGroupsEntity();
				userMenuGroup.setEpersonId(epersonEntity.getEpersonId());
				userMenuGroup.setGroupShortcut(shortcut);
				
				this.epersonMenuGroupsRepository.save(userMenuGroup);
			}
		}	
	}
}
